var packageName = "/excel-killer";
// var rootUrl = "C:/Users/123/Desktop/test/"
var fs = require('fs');
var path = require('path');
// var Electron = require('electron');

module.exports = {
    created(rootPath){
        // CfgUtil = require(rootPath + packageName + '/core/CfgUtil.js');
        excelItem = require(rootPath + packageName + '/panel/item/excelItem.js');
        nodeXlsx = require(rootPath + packageName + '/node_modules/node-xlsx');
        uglifyJs = require(rootPath + packageName + '/node_modules/uglify-js');
        fsExtra = require(rootPath + packageName + '/node_modules/fs-extra');
        jsonBeautifully = require(rootPath + packageName + '/node_modules/json-beautifully');
        chokidar = require(rootPath + packageName + '/node_modules/chokidar');

        this.rootPath = rootPath;
        this.jsonSavePath = rootPath + '/jsonConfig';//json文件存放目录
        var fileName = path.basename(rootPath);
        // this.excelRootPath = rootPath.replace("/" + fileName, "");
        this.excelRootPath = rootPath + "/excel";

        this.isMergeJson = true;
        this.isFormatJson = false;// 是否格式化Json

        this.isJsonAllCfgFileExist = false;// 是否单一配置文件存在
        this.jsonAllCfgFileName = null;// json配置文件名

        this.jsSavePath = null;// 插件资源目录
        this.jsFileName = null;//js配置文件名
        this.isJsFileExist = false;
        this.isFormatJsCode = false;
        this.excelArray = [];
        this.excelFileArr = [];

        this.tarnsList = require(this.rootPath + "/a_transList");
        this.nameList = require(this.rootPath + "/a_nameList");
        // this.readFile()
        this._initPluginCfg();
    },

    readFile(){
        var fs=require('fs');
        var self = this
        fs.readFile(this.rootPath + "/transList.txt",'utf-8',function(err,data){
            if(err){
                console.error(err);
            }
            else{
                self.tarnsList.push(data)
            }
        });
    },

    _watchDir(event, filePath) {
        // console.log(event, filePath);
        let ext = path.extname(filePath);
        if (ext === ".xlsx" || ext === ".xls") {
            this._onAnalyzeExcelDirPath(this.excelRootPath);
        }
    },

    _getExcellArray(allFileArr, fileName, dir){
        var transName1 = fileName + ".xlsx"
        var transName2 = fileName + ".xls"
        for (let k in allFileArr) {
            let file = allFileArr[k];
            let extName = path.extname(file);
            let fileName = path.basename(file);

            if (transName1 == fileName || transName2 == fileName) {
                // excelFileArr.push(file);
                // 组装显示的数据
                let excelSheetArray = [];
                let sheetDuplicationChecker = {};//表单重名检测
                let itemFullPath = file;
                // console.log("excel : " + itemFullPath);

                let excelData = nodeXlsx.parse(itemFullPath);
                //todo 检测重名的sheet
                for (let j in excelData) {
                    let itemData = {
                        isUse: true,
                        fullPath: file,
                        name: "name",
                        sheet: excelData[j].name
                    };
                    itemData.name = itemFullPath.substr(dir.length + 1, itemFullPath.length - dir.length);

                    if (excelData[j].data.length === 0) {
                        console.log("[Error] 空Sheet: " + itemData.name + " - " + itemData.sheet);
                        continue;
                    }

                    if (sheetDuplicationChecker[itemData.sheet]) {
                        //  重名sheet问题
                        console.log("[Error ] 出现了重名sheet: " + itemData.sheet);
                        console.log("[Sheet1] " + sheetDuplicationChecker[itemData.sheet].fullPath);
                        console.log("[Sheet2] " + itemFullPath);
                        console.log("请仔细检查Excel-Sheet!");
                    } else {
                        sheetDuplicationChecker[itemData.sheet] = itemData;
                        excelSheetArray.push(itemData);
                    }
                }

                return excelSheetArray
            }
        }
    },

    // 查找出目录下的所有excel文件
    _onAnalyzeExcelDirPath(dir) {
        if (!dir) {
            return
        }
        // 查找json文件
        let allFileArr = [];
        let excelFileArr = [];
        // 获取目录下所有的文件
        readDirSync(dir);
        // 过滤出来.xlsx的文件
        for (var i = 0; i < this.tarnsList.length; i++) {
            var fileName = this.tarnsList[i]

            this.excelArray = this._getExcellArray(allFileArr, fileName, dir) || [];
            this.jsonAllCfgFileName = this.nameList[this.tarnsList[i]] || "未命名"
            this.onBtnClickGen()
        }


        this.excelFileArr = excelFileArr;


        function readDirSync(dirPath) {
            let dirInfo = fs.readdirSync(dirPath);
            for (let i = 0; i < dirInfo.length; i++) {
                let item = dirInfo[i];
                let itemFullPath = path.join(dirPath, item);
                let info = fs.statSync(itemFullPath);
                if (info.isDirectory()) {
                    // console.log('dir: ' + itemFullPath);
                    readDirSync(itemFullPath);
                } else if (info.isFile()) {
                    let headStr = item.substr(0, 2);
                    if (headStr === "~$") {
                        console.log("检索到excel产生的临时文件:" + itemFullPath);
                    } else {
                        allFileArr.push(itemFullPath);
                    }
                }
            }
        }
    },

    _initPluginCfg() {
        console.log("initCfg");
        
        if (fs.existsSync(this.excelRootPath)) {
            // this._onAnalyzeExcelDirPath(this.excelRootPath);
            chokidar.watch(this.excelRootPath).on('all', this._watchDir.bind(this));
        } else {

        }
        this.jsFileName = "未命名";
        this.jsonAllCfgFileName = "未命名";
        // this.isMergeJson = true;
        // this.isFormatJsCode = false;
        // this.isFormatJson = false;

        // this.jsonSavePath = "E:\\work\\project\\assets\\resources\\jsonConfig";
    },

    _getJsonSaveData(excelData, itemSheet) {
        let title = excelData[0];
        let desc = excelData[1];
        let ret = null;
        let useFormat1 = false;
        if (useFormat1) {
            let saveData1 = [];// 格式1:对应的为数组
            for (let i = 2; i < excelData.length; i++) {
                let lineData = excelData[i];
                if (lineData.length < title.length) {
                    continue;
                } else if (lineData.length > title.length) {
                    continue;
                }

                let saveLineData = {};
                for (let j = 0; j < title.length; j++) {
                    let key = title[j];
                    let value = lineData[j];
                    if (value === undefined) {
                        value = "";
                    }
                    // this._addLog("" + value);
                    saveLineData[key] = value;
                }
                saveData1.push(saveLineData);
            }
            ret = saveData1;
        } else {
            let saveData2 = {};// 格式2:id作为索引
            for (let i = 2; i < excelData.length; i++) {
                let lineData = excelData[i];
                if (lineData.length < title.length) {
                    continue;
                } else if (lineData.length > title.length) {
                    continue;
                }
                let saveLineData = {};
                for (let j = 1; j < title.length; j++) {
                    let key = title[j];
                    let value = lineData[j];
                    if (value === undefined) {
                        value = "";
                    }
                    // this._addLog("" + value);
                    saveLineData[key] = value;
                }
                if (lineData[0]) {
                    saveData2[lineData[0].toString()] = saveLineData;
                }
                
            }
            ret = saveData2;
        }
        return ret;
    },

    // 生成配置
    onBtnClickGen() {
        // 参数校验
        if (this.excelArray.length <= 0) {
            console.log("未发现要生成的配置!");
            return;
        }

        // if (this.isMergeJson) {
        //     if (this.jsonAllCfgFileName.length <= 0) {
        //         console.log("请输入要保存的json文件名!");
        //         return;
        //     }
        // }
        if (this.jsFileName.length <= 0) {
            console.log("请输入要保存的js文件名!");
            return;
        }


        this.logView = "";
        // 删除老的配置
        // fsExtra.emptyDirSync(this.jsonSavePath);
        // fsExtra.emptyDirSync(this.jsSavePath);
        let jsSaveData = {};// 保存的js数据
        let jsonAllSaveData = {};// 保存的json数据
        for (let k in this.excelArray) {
            let itemSheet = this.excelArray[k];
            if (itemSheet.isUse) {
                let excelData = nodeXlsx.parse(itemSheet.fullPath);
                let sheetData = null;
                for (let j in excelData) {
                    if (excelData[j].name === itemSheet.sheet) {
                        sheetData = excelData[j].data;
                    }
                }
                if (sheetData) {
                    if (sheetData.length > 2) {
                        // 保存为json
                        let jsonSaveData = this._getJsonSaveData(sheetData, itemSheet);
                        if (this.isMergeJson) {
                            jsonAllSaveData[itemSheet.sheet] = jsonSaveData;
                        } else {
                            let saveStr = JSON.stringify(jsonSaveData);
                            if (this.isFormatJson) {// 格式化json
                                saveStr = jsonBeautifully(saveStr);
                            }
                            let saveFileFullPath = path.join(this.jsonSavePath, itemSheet.sheet + ".json");
                            fs.writeFileSync(saveFileFullPath, saveStr);
                            console.log("[Json]:" + saveFileFullPath);
                        }
                        // 保存为js
                        // let sheetJsData = this._getJavaScriptSaveData(sheetData, itemSheet);
                        // // 检测重复问题
                        // if (jsSaveData[itemSheet.sheet] === undefined) {
                        //     jsSaveData[itemSheet.sheet] = sheetJsData;
                        // } else {
                        //     console.log("发现重名sheet:" + itemSheet.name + "(" + itemSheet.sheet + ")");
                        // }
                    } else {
                        console.log("行数低于2行,无效sheet:" + itemSheet.sheet);
                    }
                } else {
                    console.log("未发现数据");
                }

            } else {
                console.log("忽略配置: " + itemSheet.fullPath + ' - ' + itemSheet.sheet);
            }
        }
        // =====================>>>>  保存json文件   <<<=================================
        if (this.isMergeJson) {
            let saveFileFullPath = path.join(this.jsonSavePath, this.jsonAllCfgFileName + ".json");
            let str = JSON.stringify(jsonAllSaveData);
            if (this.isFormatJson) {
                str = jsonBeautifully(str);
            }
            fs.writeFileSync(saveFileFullPath, str);
            console.log("[Json]:" + saveFileFullPath);
        }
        // =====================>>>>  保存js文件   <<<=================================
        // TODO 保证key的顺序一致性
        // console.log("aaaa" + "aaaaaaaaaaaaaaaaaa", this.jsSavePath, this.jsFileName);
        // let saveFileFullPath = path.join(this.jsSavePath, this.jsFileName + ".js");
        // let saveStr = "module.exports = " + JSON.stringify(jsSaveData) + ";";
        // if (this.isFormatJsCode) {// 保存为格式化代码
        //     let ast = uglifyJs.parse(saveStr);
        //     let ret = uglifyJs.minify(ast, {
        //         output: {
        //             beautify: true,//如果希望得到格式化的输出，传入true
        //             indent_start: 0,//（仅当beautify为true时有效） - 初始缩进空格
        //             indent_level: 4,//（仅当beautify为true时有效） - 缩进级别，空格数量
        //         }
        //     });
        //     if (ret.error) {
        //         console.log('error: ' + ret.error.message);
        //     } else if (ret.code) {
        //         fs.writeFileSync(saveFileFullPath, ret.code);
        //         console.log("[JavaScript]" + saveFileFullPath);
        //     } else {
        //         console.log(JSON.stringify(ret));
        //     }
        // } else {// 保存为单行代码
        //     fs.writeFileSync(saveFileFullPath, saveStr);
        //     console.log("[JavaScript]" + saveFileFullPath);
        // }
        console.log("全部转换完成!");
        // this.checkJsFileExist();
        // this.checkJsonAllCfgFileExist();
    },
}